from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin
import json
from .serializer import BookSerializer
from books.models import BookInfo


class Books(GenericAPIView, ListModelMixin, CreateModelMixin):
    serializer_class = BookSerializer
    queryset = BookInfo.objects.all()
    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.list(request)
class Book(GenericAPIView, RetrieveModelMixin):
    serializer_class = BookSerializer
    queryset = BookInfo.objects.all()

    def get(self, request, pk):
        return self.retrieve(request)
    def put(self, request, pk):
        data = request.body.decode()
        data_dict = json.loads(data)
        try:
            book = BookInfo.objects.get(pk=pk)
        except:
            return Response('错误')
        # 验证数据
        # ser = BooksSerializer(data=data_dict)
        # 修改时
        ser = BookSerializer(book, data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return Response(ser.data)